<?php
// 调试删除功能的专用API
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

require_once '../config.php';

// 添加详细的调试日志
function debugLog($message) {
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] DEBUG: $message" . PHP_EOL;
    error_log($logMessage, 3, '../logs/debug.log');
    echo "<!-- DEBUG: $message -->" . PHP_EOL;
}

handleCORS();

debugLog("调试删除API开始");

class DebugDeleteAPI {
    private $db;
    
    public function __construct() {
        try {
            $this->db = Database::getInstance()->getConnection();
            debugLog("数据库连接成功");
        } catch (Exception $e) {
            debugLog("数据库连接失败: " . $e->getMessage());
            sendErrorResponse("数据库连接失败: " . $e->getMessage());
        }
    }
    
    public function handleRequest() {
        debugLog("处理请求开始");
        debugLog("请求方法: " . $_SERVER['REQUEST_METHOD']);
        debugLog("请求URI: " . $_SERVER['REQUEST_URI']);
        debugLog("GET参数: " . json_encode($_GET));
        debugLog("POST参数: " . json_encode($_POST));
        
        // 获取请求头
        $headers = getallheaders();
        debugLog("请求头: " . json_encode($headers));
        
        // 获取请求体
        $input = file_get_contents('php://input');
        debugLog("请求体: " . $input);
        
        try {
            $requestData = getRequestData();
            debugLog("解析的请求数据: " . json_encode($requestData));
            
            $action = $_GET['action'] ?? $_POST['action'] ?? $requestData['action'] ?? '';
            $id = $_GET['id'] ?? $_POST['id'] ?? $requestData['id'] ?? '';
            
            debugLog("Action: $action, ID: $id");
            
            if ($action === 'delete' && $id) {
                $this->debugDeleteBookmark($id);
            } else {
                debugLog("参数无效 - action: $action, id: $id");
                sendErrorResponse("参数无效");
            }
        } catch (Exception $e) {
            debugLog("处理请求异常: " . $e->getMessage());
            debugLog("异常堆栈: " . $e->getTraceAsString());
            sendErrorResponse("处理请求失败: " . $e->getMessage());
        }
    }
    
    private function debugDeleteBookmark($id) {
        debugLog("开始删除收藏，ID: $id");
        
        try {
            // 1. 验证认证
            debugLog("验证认证开始");
            $user = $this->requireAuth();
            debugLog("认证成功，用户ID: " . $user['id'] . ", 用户名: " . $user['username']);
            
            // 2. 验证ID
            $id = intval($id);
            debugLog("转换后的ID: $id");
            if ($id <= 0) {
                debugLog("ID无效: $id");
                sendErrorResponse('无效的收藏ID', 400);
            }
            
            // 3. 检查收藏是否存在
            debugLog("查询收藏是否存在");
            $stmt = $this->db->prepare("SELECT id, name FROM bookmarks WHERE id = ? AND user_id = ?");
            $stmt->execute([$id, $user['id']]);
            $bookmark = $stmt->fetch();
            
            if (!$bookmark) {
                debugLog("收藏不存在或无权限访问");
                sendErrorResponse('收藏不存在或无权限访问', 404);
            }
            
            debugLog("找到收藏: " . json_encode($bookmark));
            
            // 4. 执行删除
            debugLog("执行删除操作");
            $stmt = $this->db->prepare("DELETE FROM bookmarks WHERE id = ? AND user_id = ?");
            $result = $stmt->execute([$id, $user['id']]);
            $rowCount = $stmt->rowCount();
            
            debugLog("删除结果: " . ($result ? 'true' : 'false'));
            debugLog("影响行数: $rowCount");
            
            if ($result && $rowCount > 0) {
                debugLog("删除成功");
                logActivity("用户删除收藏: {$user['username']} - {$bookmark['name']}");
                
                $response = [
                    'success' => true,
                    'message' => '收藏删除成功',
                    'data' => [
                        'deleted_id' => $id,
                        'deleted_name' => $bookmark['name']
                    ],
                    'debug_info' => [
                        'user_id' => $user['id'],
                        'bookmark_id' => $id,
                        'timestamp' => date('Y-m-d H:i:s')
                    ]
                ];
                
                debugLog("准备发送成功响应: " . json_encode($response));
                sendJsonResponse($response);
            } else {
                debugLog("删除失败，可能收藏不存在");
                sendErrorResponse('删除失败，收藏可能不存在', 404);
            }
        } catch (Exception $e) {
            debugLog("删除异常: " . $e->getMessage());
            debugLog("异常文件: " . $e->getFile() . " 行号: " . $e->getLine());
            debugLog("异常堆栈: " . $e->getTraceAsString());
            sendErrorResponse('删除收藏失败: ' . $e->getMessage());
        }
    }
    
    private function requireAuth() {
        debugLog("开始认证验证");
        
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        debugLog("认证头: $authHeader");
        
        if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            debugLog("未找到Bearer令牌");
            sendErrorResponse('未提供认证令牌', 401);
        }
        
        $token = $matches[1];
        debugLog("提取的令牌: " . substr($token, 0, 20) . "...");
        
        $stmt = $this->db->prepare("
            SELECT u.*, s.expires_at 
            FROM users u 
            JOIN user_sessions s ON u.id = s.user_id 
            WHERE s.session_token = ? AND s.expires_at > NOW()
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if (!$user) {
            debugLog("用户令牌无效或已过期");
            sendErrorResponse('无效或过期的认证令牌', 401);
        }
        
        if ($user['status'] !== 'active') {
            debugLog("用户账户已被禁用");
            sendErrorResponse('账户已被禁用', 403);
        }
        
        debugLog("认证成功");
        return $user;
    }
}

// 创建日志目录
if (!file_exists('../logs')) {
    mkdir('../logs', 0755, true);
    debugLog("创建日志目录");
}

debugLog("开始处理调试删除请求");
$api = new DebugDeleteAPI();
$api->handleRequest();
debugLog("调试删除API结束");
?>


















